import {defineStore} from "pinia";
import {ResetPasswordType, SetRolesType, UserQueryVo, UserVo} from "@/api/sys/admin/user/types";
import {RoleVo} from "@/api/sys/admin/role/types";
import {batchDeleteUserApi, getUserByIdApi, getUserListApi} from "@/api/sys/admin/user";
import {getRoleIdsByUserIdApi, getRolesApi} from "@/api/sys/admin/role";
import {cloneDeep, initPageQuery} from "@/utils/common-fn";
import {useGetOptions} from "@/utils/use/use-get-options";
import {DictType, OpenFormType} from "@/utils/enum-type";
import {Ref} from "vue";
import {openConfirm} from "@/components/MyComponent/XMessageBox";

// 用户页面
export const useUserViewStore = defineStore('userView', () => {
    /**
     * 公共
     */
        // 获取options
    let allOptions = useGetOptions(DictType.Status, DictType.Gender);
    const statusOptions = computed(() => allOptions.value[0])
    const genderOptions = computed(() => allOptions.value[1])

    const title = '用户'
    // 打开表单类型
    let openFormType: Ref<OpenFormType> = ref(OpenFormType.Add)
    // 初始化
    const initForm: UserVo = {id: 0, username: '', password: '', nickname: '', gender: 1, email: '', status: 1}
    /**
     * table相关
     */

        // table数据
    let tableData: Ref<UserVo[]> = ref([])
    // 总数
    const total = ref(0)
    // 分页信息,以及查询条件,用于发送api
    const queryData = reactive(initPageQuery<UserQueryVo>())
    // 批量选择的用户id
    const batchSelectedIds: Ref<number[]> = ref([])
    /**
     * 密码相关
     */
        // 修改密码弹出框可见
    const rePasswordVisible = ref(false)

    // 重置密码表单
    const rePasswordForm: ResetPasswordType = reactive({id: 0})
    /**
     * 表单相关
     */

        // 角色选择options
    let roleOptions: Ref<RoleVo[]> = ref([])
    // 表单可见
    const visible = ref(false)
    // 表单数据
    const formData: Ref<UserVo> = ref(cloneDeep(initForm))

    /**
     * 分配角色
     */
    const setRolesVisible = ref(false)
    const setRolesForm: Ref<SetRolesType> = ref({})

    /**
     * 方法相关
     */

    // 设置编辑对话框可见
    function setVisible(value: boolean) {
        visible.value = value
    }

    // 设置打开或者关闭修改密码框
    function setRePasswordVisible(bolValue: boolean) {
        rePasswordVisible.value = bolValue
    }

    // 设置分分配角色可见
    function setSetRolesVisible(bolValue: boolean) {
        setRolesVisible.value = bolValue
    }

    /**
     * 获取列表
     */
    async function getList() {
        [tableData.value, total.value] = await getUserListApi(queryData)
        allOptions = useGetOptions(DictType.Status, DictType.Gender);
    }

    // 批量选择用户id
    function handleBatchSelect(users: UserVo[]) {
        batchSelectedIds.value = users.map(user => user.id)
    }

    // 打开表单
    function open(): void
    async function open(id: number): Promise<void>
    async function open(id?: number) {
        if (id) {
            // 编辑
            formData.value = await getUserByIdApi(id)
            openFormType.value = OpenFormType.Edit
        } else {
            // 新增
            formData.value = cloneDeep(initForm)
            openFormType.value = OpenFormType.Add
        }
        setVisible(true)
    }

    // 打开密码重置
    function openRePassword(id: number) {
        rePasswordForm.id = id
        setRePasswordVisible(true)
    }

    // 打开分配角色
    async function openSetRoles(id: number) {
        // 用户信息
        // 角色下拉框
        // 获取用户拥有的角色ids
        [formData.value, roleOptions.value, setRolesForm.value.roleIds] =
            await Promise.all([getUserByIdApi(id), getRolesApi(), getRoleIdsByUserIdApi(id)])
        setRolesForm.value.id = id
        setRolesVisible.value = true
    }

    // 批量删除用户
    async function batchDelete() {
        if (batchSelectedIds.value.length === 0) {
            return ElMessage.info('请至少选择一个用户再操作')
        }
        if (await openConfirm('确定批量删除这些用户')) {
            await batchDeleteUserApi(batchSelectedIds.value)
            ElMessage.success('删除成功')
            await getList()
        }
    }

    return {
        tableData, rePasswordForm, queryData, total, rePasswordVisible, roleOptions, title,
        formData, visible, setRolesVisible, setRolesForm, genderOptions, statusOptions, openFormType,
        openSetRoles, setSetRolesVisible, getList, setRePasswordVisible, setVisible, open, openRePassword,
        handleBatchSelect,batchDelete
    }
})